﻿using System;
using System.Web;
using ASPNETVN.PORTAL.Components.Helpers;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.UI;
using ASPNETVN.PORTAL.Modules.CMS.Components;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;

namespace ASPNETVN.PORTAL.Modules.CMS.Controls
{
    public partial class AddEditItem : AddEditItemControl
    {
        protected override void OnInit(EventArgs e)
        {
            this.ButtonUpdate = btnUpdate;
            this.ButtonDelete = btnDelete;
            this.ButtonCancel = btnCancel;

            this.Update += AddEditItem_Update;
            this.Delete += AddEditItem_Delete;
            base.OnInit(e);
        }

        void AddEditItem_Delete(object sender, EventArgs e)
        {
            if (this.ItemID > 0)
            {
                Components.Item item = Components.Item.Load(this.ItemID);
                item.Delete();
                string filename = item.ImagePath;
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }
                this.ReturnToReferrerPage();
            }
        }

        void AddEditItem_Update(object sender, EventArgs e)
        {
            Components.Item item = new Components.Item();
            if (this.ItemID > 0)
            {
                item = Components.Item.Load(this.ItemID);
            }

            int categoryID = Convert.ToInt32(cbCategory.SelectedValue);
            int groupID = Convert.ToInt32(cbGroup.SelectedValue);

            // Lĩnh vực.
            item.CategoryID = categoryID;

            // Nhóm bài viết.
            item.GroupID = groupID;

            // Tiêu đề.
            item.Title = txtTitle.Text;

            // Trích yếu nội dung.
            item.SubTitle = txtSubTitle.Text;

            // Từ khóa.
            item.Keywords = txtKeywords.Text;

            // Tác giả.
            item.Authors = txtAuthors.Text;

            // Nội dung.
            item.Body = HttpUtility.HtmlEncode(txtContent.Value);

            // Trạng thái.
            item.Status = cbStatus.SelectedValue;

            // Vị trí hiển thị.
            item.DisplayType = ddlDisplayType.SelectedValue;

            // Hình minh họa.


            // Lưu tập tin.
            string fileUrl = string.Empty;
            if (FileUploadAttachment.HasFile)
            {
                // Delete before upload.
                if (item.ImagePath.Length > 0)
                {
                    try
                    {
                        string filename = this.Server.MapPath(item.ImagePath);
                        if (File.Exists(filename))
                        {
                            File.Delete(filename);
                        }
                    }
                    catch
                    {

                    }
                }

                string physicalDirectory = Server.MapPath("~/Modules/ASPNETVN.PORTAL.Modules.CMS/Uploads/" + this.ModuleID);
                // Tạo thư mục để chứa tập tin.
                if (Directory.Exists(physicalDirectory) == false)
                {
                    Directory.CreateDirectory(physicalDirectory);
                }

                string physicalPath = physicalDirectory + "\\" + this.FileUploadAttachment.FileName;

                int i = 1;
                while (File.Exists(physicalPath))
                {
                    physicalPath = physicalDirectory + "\\" + i + "_" + this.FileUploadAttachment.FileName;
                    i++;
                }
                FileInfo fi = new FileInfo(physicalPath);
                //FileUploadAttachment.SaveAs(physicalPath);
                fileUrl = "~/Modules/ASPNETVN.PORTAL.Modules.CMS/Uploads/" + this.ModuleID + "/" + fi.Name;

                // need to caculate correct width and height
                int widthMax = Convert.ToInt32(this.Settings["Picture.Width"].ToString());
                int heightMax = Convert.ToInt32(this.Settings["Picture.Height"].ToString());

                if (ddlDisplayType.SelectedValue == "ONE")
                {
                    widthMax = 400;
                    heightMax = 400;
                }

                Image fullPicture;
                try
                {
                    // New image size.
                    fullPicture = new Bitmap(FileUploadAttachment.PostedFile.InputStream);
                    Image original = ImageHelper.ResizeImage(fullPicture, widthMax, heightMax, ImageResizeOption.MaintainAspectWidth);
                    fullPicture.Dispose();

                    string ext = fi.Extension;
                    switch (ext.ToLower())
                    {
                        case ".jpg":
                            original.Save(physicalPath, ImageFormat.Jpeg);
                            break;
                        case ".png":
                            original.Save(physicalPath, ImageFormat.Png);
                            break;
                        case ".gif":
                            original.Save(physicalPath, ImageFormat.Gif);
                            break;
                        case ".bmp":
                            original.Save(physicalPath, ImageFormat.Bmp);
                            break;
                    }
                    original.Dispose();
                }
                catch (Exception ex)
                {
                    throw new Exception("Error in create thumbnail: " + ex.Message);
                }
            }

            if (FileUploadAttachment.HasFile)
                item.ImagePath = fileUrl;

            if (this.ItemID == 0)
            {
                item.CreatedBy = PortalSecurity.CurrentUser.Identity.Email;
                item.CreatedDate = DateTime.Now;

                if (Convert.ToBoolean(this.Settings["RequireApprobation"].ToString()) == false)
                {
                    item.Status = "PUBLISHED";
                    item.ApprovedDate = DateTime.Now;
                    item.ApprovedBy = PortalSecurity.CurrentUser.Identity.Email;
                    item.PublishedDate = DateTime.Now;
                    item.ExpiredDate = DateTime.MaxValue;
                }
                this.ItemID = item.Insert();
            }
            else
            {
                item.ID = this.ItemID;
                if (Convert.ToBoolean(this.Settings["RequireApprobation"].ToString()) == false)
                {
                    item.Status = "PUBLISHED";
                }
                item.Update();
            }
            if (Convert.ToBoolean(this.Settings["RequireApprobation"].ToString()))
            {
                Response.Redirect(HttpUrlBuilder.BuildAddEditUrl(this.ModuleID, this.ItemID, "ApproveItem"));
            }
            else
            {
                this.ReturnToReferrerPage();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PORTAL.Components.Share.Category.BuildDropDownListControl(ref cbCategory, this.ModuleID);

                cbGroup.DataSource = Group.SelectAll(this.ModuleID);
                cbGroup.DataBind();

                Hashtable settings = this.Settings;
                string[] displaytypes = settings["DisplayType"].ToString().Split(';');
                foreach (string item in displaytypes)
                {
                    ddlDisplayType.Items.Add(item);
                }

                if (this.ItemID > 0)
                {
                    Components.Item item = Components.Item.Load(this.ItemID);
                    if (item != null)
                    {
                        // Lĩnh vực.    
                        cbCategory.SelectedValue = item.CategoryID.ToString();

                        // Nhóm bài viết.
                        cbGroup.SelectedValue = item.GroupID.ToString();

                        // Tiêu đề.
                        txtTitle.Text = item.Title;

                        // Trích yếu nội dung.
                        txtSubTitle.Text = item.SubTitle;

                        // Từ khóa.
                        txtKeywords.Text = item.Keywords;

                        // Tác giả.
                        txtAuthors.Text = item.Authors;

                        // Nội dung.
                        txtContent.Value = HttpUtility.HtmlDecode(item.Body);

                        // Đánh giá.
                        // Lượt xem.
                        // Vị trí hiển thị.
                        ddlDisplayType.SelectedValue = item.DisplayType;
                    }
                }
                else
                {
                    btnDelete.Visible = false;
                }

                //Không hiển thị trạng thái khi RequireApprobation=false                        
                trStatus.Visible = Convert.ToBoolean(this.Settings["RequireApprobation"].ToString());
            }
        }
    }
}